/*  This file is part of -_-.

    -_- is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    -_- is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with -_-.  If not, see <http://www.gnu.org/licenses/>.

    Copyright 2012-2013 Oliver Katz */

#include "bus.h"

z_data z_bus_create_program(char *name, char *addr, int port)
{
	z_list tmp = z_list_init(3);
	z_list_append(&tmp, z_data_wrap(name, Z_TYPEID_STR, (strlen(name)+1)*sizeof(char)), 1);
	z_list_append(&tmp, z_data_wrap(addr, Z_TYPEID_STR, (strlen(addr)+1)*sizeof(char)), 1);
	z_list_append(&tmp, z_data_wrap(&port, Z_TYPEID_INT, sizeof(int)), 1);
	return z_data_wrap(&tmp, Z_TYPEID_NULL, sizeof(z_list));
}

char *strtok_r(char *str, const char *delim, char **saveptr);

int z_bus_parse_programs(char *buf, z_list *dst)
{
	char *save_newline;
	for (char *p = strtok_r(buf, "\n", &save_newline); p != NULL; p = strtok_r(NULL, "\n", &save_newline))
	{
		char *port = strchr(p, ':')+1;
		*(strchr(p, ':')) = 0;
		char *addr = strchr(p, '@')+1;
		*(strchr(p, '@')) = 0;
		char *name = p;

		z_list_append(dst, z_bus_create_program(name, addr, atoi(port)), 16);
	}

	return 0;
}

char *z_bus_list_programs(z_list src)
{
	char *buf = (char *)malloc(sizeof(char)*(32*z_list_size(&src)));
	buf[0] = 0;

	for (z_size i = 0; i < z_list_size(&src); i++)
	{
		z_list *tmp = (z_list *)z_list_get(&src, i).src;
		sprintf(buf+strlen(buf), "%s@%s:%i\n", (char *)z_list_get(tmp, 0).src, (char *)z_list_get(tmp, 1).src, *(int *)z_list_get(tmp, 2).src);
	}

	return buf;
}
